#include "oxford-word-provider.h"

using namespace Oxford;

WordProvider::WordProvider()
{
    databaseManager = new Core::DatabaseManager("Oxford");
}

WordProvider::~WordProvider()
{
    delete databaseManager;
}

Word WordProvider::getWord(const QString &wordName) const
{
    QString firstLetter = wordName.left(1);
    QString twoLetters = wordName.left(2);
    QString threeLetters = wordName.left(3);

    if (firstLetter.length() == 1)
        databaseManager->startSubStorage(firstLetter);
    if (twoLetters.length() == 2)
        databaseManager->startSubStorage(twoLetters);
    if (threeLetters.length() == 3)
        databaseManager->startSubStorage(threeLetters);


    Word result = databaseManager->exists(wordName) ? Word::fromString(databaseManager->read(wordName)) : Word();

    if (threeLetters.length() == 3)
        databaseManager->finishSubStorage();
    if (twoLetters.length() == 2)
        databaseManager->finishSubStorage();
    if (firstLetter.length() == 1)
        databaseManager->finishSubStorage();

    return result;
}

bool WordProvider::wordExists(const QString &wordName) const
{
    QString firstLetter = wordName.left(1);
    QString twoLetters = wordName.left(2);
    QString threeLetters = wordName.left(3);

    if (firstLetter.length() == 1)
        databaseManager->startSubStorage(firstLetter);
    if (twoLetters.length() == 2)
        databaseManager->startSubStorage(twoLetters);
    if (threeLetters.length() == 3)
        databaseManager->startSubStorage(threeLetters);


    bool result = databaseManager->exists(wordName);

    if (threeLetters.length() == 3)
        databaseManager->finishSubStorage();
    if (twoLetters.length() == 2)
        databaseManager->finishSubStorage();
    if (firstLetter.length() == 1)
        databaseManager->finishSubStorage();

    return result;
}
